package com.h4313.ghome.io;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.h4313.ghome.R;
import com.h4313.ghome.model.Capteur;
import com.h4313.ghome.model.Module;

import android.content.Context;
import android.os.AsyncTask;

public class ModulesTask extends AsyncTask<String, Void, String>{
	
	public interface ModulesCallback {
		public void onAllModulesFound(List<Module> modules);
	}

	private List<Module> mModules;
	private WeakReference<ModulesCallback> mCallback;
	
	public ModulesTask(ModulesCallback cb) {
		mCallback = new WeakReference<ModulesTask.ModulesCallback>(cb);
	}
	
	@Override
	protected String doInBackground(String... urls) {
		try{
			String contentAsString = NetworkHelper.downloadUrl(urls[0], 60000, 60000);
			mModules = new ArrayList<Module>();
			JSONArray root = new JSONArray(contentAsString);
			//JSON contains an array of modules (with type/id keys)
			for (int i = 0; i < root.length(); i++) {
				JSONObject jm = root.getJSONObject(i);
				Module m = new Module();
				m.setId(jm.getInt("rowid"));
				m.setType(jm.getString("module"));
				mModules.add(m);
			}
			// FIXME remove in prod
//			Module morning = new Module();
//			morning.setId(4);
//			morning.setType("morning");
//			mModules.add(morning);
			
			return "OK";
		} catch (IOException e){
			System.out.print("Unable to retrieve data. URL may be invalid.");
			e.printStackTrace();
			return null;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	protected void onPostExecute(String result) {
		if (mCallback.get() != null && result != null) {
			// has been updated during doInBackground()
			mCallback.get().onAllModulesFound(mModules);
		}
	}
}
